<template>
  <div
    ref="xe2Container"
    style="position: absolute; width: 100%; height: 100%"
  ></div>
</template>
<script setup lang="ts">
import { ref, onMounted } from "vue";
import {
  ESObjectsManager,
  ESGeoDiv,
} from "esobjs-xe2-plugin/dist-node/esobjs-xe2-plugin-main";
import apiPage from "@/api/page";
//import { getSceneTree } from '@/utils/sceneTool'

interface PageInfoResponse {
  code: number;
  data?: {
    content: string;
  };
}

const xe2Container = ref<HTMLElement | null>(null);
const objm = new ESObjectsManager();
// @ts-ignore
window.ESObjectsManager = objm;

const getUrlParams = (url: string): Record<string, string> => {
  const urlStr = url.split("?")[1] || "";
  const urlSearchParams = new URLSearchParams(urlStr);
  return Object.fromEntries(urlSearchParams.entries());
};

onMounted(async () => {
  if (!xe2Container.value) return;
  if (!window.ESObjectsManager) {
    console.error("ESObjectsManager is not defined.");
    return;
  }

  try {
    const czmViewer = window.ESObjectsManager.createCesiumViewer(
      xe2Container.value,
      "12345"
    );

    const params = getUrlParams(window.location.hash || window.location.search);
    const res: PageInfoResponse = await apiPage.getPageInfo({
      name: params.name || "28e5282f-eff0-4e48-a8a3-82b9da0acdd7",
      namespace: `/insightarts-page`,
      version: "v0",
    });

    if (res.code === 2000010000) {
      const content = res.data?.content;
      if (content) {
        const scene = JSON.parse(content);
        window.ESObjectsManager.json = { ...scene };

        czmViewer.flyIn(scene.lastView.position, scene.lastView.rotation, 3);
        // 监听视口状态
        czmViewer.statusChanged.don((status) => {
          if (status === "Created") {
            czmViewer.flyIn(
              scene.lastView.position,
              scene.lastView.rotation,
              3
            );
          }
        });
      }
    }
  } catch (error) {
    console.error("An error occurred:", error);
  }

  if (window.ESObjectsManager) {
    window.ESObjectsManager.jsonLoadingEvent.don((e) => {
      if (e.type !== "loaded") return;
      // getSceneTree();
    });
  }
});
</script>

<style scoped></style>
